package com.it.archives.service;

import com.it.archives.model.User;
import com.it.archives.rpc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@Service
public class CommodityApiService {

    @Autowired
    UserService userService;
    LinkedBlockingQueue queue = new LinkedBlockingQueue();


    class Request{

        String id;
        CompletableFuture<User> future;
    }

    @PostConstruct
    public void init(){
        ScheduledExecutorService poolExecutorService = new ScheduledThreadPoolExecutor(1);

        poolExecutorService.scheduleAtFixedRate(() -> {
            int size = queue.size();
            if(size == 0){
                // 队列不存在跳出
                return;
            }
            List<Request> requests = new ArrayList<>();
            for (int i = 0; i < size; i++){
                Request request = (Request) queue.poll();
                requests.add(request);
            }
            System.out.println("批量处理数量"+ size);

            List<String> idList = new ArrayList<>();
            // 处理数组id
            for (Request request : requests){
                idList.add(request.id);
            }
            User user = new User();//idList
            List<User> reponse = userService.queryUserListByParam(user);
            Map<String,Object> map = new HashMap<>();
            for (User userRep : reponse){
                map.put(userRep.getId(),userRep);
            }

            for (Request request : requests){
                User list =  (User) map.get(request.id);
                System.out.println("批量处理数量"+ request.id);

                request.future.complete(list);
            }



        },0,2, TimeUnit.SECONDS);

    }

    // 获取数据
    public User queryCommodity(String id) throws Exception{

        Request request = new Request();
        request.id = id;
        queue.add(request);

        CompletableFuture<User> future = new CompletableFuture<>();
        request.future = future;
//        List<User> list = future.get();
        User list = future.get();
        System.out.println("批量处理数量"+ list);
        return list;
      //  User user = new User();
      //  return userService.queryUserListByParam(user);
    }
}
